<template>
  <div style="height: 100%">
    <div class="flex_cm container" style="height: 100%">
      <search
        :form_data="header_list"
        @changeIsShow="
          (e) => {
            header_list[e].isShow = !header_list[e].isShow
          }
        "
        @search="search_key"
        @reset="
          header_list.forEach((item) => {
            item.value = ''
          }),
            search_key()
        "
      ></search>
      <div class="p_0_10 bg_fff flex1">
        <div class="flex_js p_10_0">
          <div class="c_666 fw">角色列表</div>
          <div class="flex">
            <el-button
              type="primary"
              v-if="has_role_list[3].has_role"
              @click="show_box = true"
              >新增角色</el-button
            >

            <setTable
              :data="header_list"
              :height_size="height_size"
              @changeShowTable="
                (e) => {
                  header_list[e].showTable = !header_list[e].showTable
                }
              "
              @resetTableSet="
                () => {
                  header_list.forEach((item) => {
                    item.showTable = true
                  })
                }
              "
              @changeHeightSize="
                (e) => {
                  height_size = e
                }
              "
            ></setTable>
          </div>
        </div>
        <el-table
          style="text-align: center"
          :data="list"
          :max-height="max_height"
          border
          highlight-current-row
          v-loading="loading"
          :default-sort="{ prop: 'name', order: 'descending' }"
          :row-style="{
            height: height_size == 2 ? '50px' : '',
          }"
          :cell-style="{
            padding: height_size == 3 ? '0' : '',
          }"
        >
          <el-table-column
            label="序号"
            type="index"
            width="100px"
          ></el-table-column>
          <el-table-column
            v-if="header_list[0].showTable"
            prop="name"
            sortable
            label="名称"
            key="name"
          >
          </el-table-column>
          <el-table-column
            v-if="header_list[1].showTable"
            prop="code"
            sortable
            label="代号"
            key="code"
          >
          </el-table-column>
          <el-table-column
            v-if="header_list[2].showTable"
            label="状态"
            sortable
            prop="status"
            key="status"
          >
            <template #default="scope: any">
              <div v-if="scope.row.status" style="color: #3580eb">已启用</div>
              <div v-else>已禁用</div>
            </template>
          </el-table-column>
          <el-table-column
            v-if="header_list[3].showTable"
            sortable
            label="角色描述"
            key="角色描述"
            ><template #default="scope: any"
              ><div class="text_over">
                <el-tooltip :content="scope.row.description" placement="bottom">
                  {{ scope.row.description }}
                </el-tooltip>
              </div></template
            ></el-table-column
          >
          <el-table-column label="操作" width="124px">
            <template #default="scope: any">
              <table_edit
                :status="true"
                :enable="scope.row.status"
                :role="has_role_list"
                @edit_item_status="
                  delete_role({
                    item: scope.row,
                    type: scope.row.status ? 2 : 1,
                  })
                "
                @edit_item="update_role(scope)"
                @delete_item="delete_role({ item: scope.row, type: 0 })"
              ></table_edit>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <el-drawer
      v-model="show_box"
      direction="rtl"
      @close="resetForm(addroleform)"
      :close-on-click-modal="false"
    >
      <template #title>
        <h4 v-if="add_form_data.id == ''">新增角色</h4>
        <h4 v-else>修改角色</h4>
      </template>
      <template #default style="font-size: 14px">
        <el-form
          :model="add_form_data"
          :rules="rules"
          ref="addroleform"
          label-width="150px"
        >
          <el-form-item label="角色名称" prop="name">
            <el-input
              v-model="add_form_data.name"
              placeholder="请输入角色名称"
              show-word-limit
              maxlength="30"
            ></el-input>
          </el-form-item>
          <el-form-item label="角色代号" prop="code">
            <el-input
              v-model="add_form_data.code"
              placeholder="请输入角色代号"
              show-word-limit
              maxlength="30"
            ></el-input>
          </el-form-item>
          <el-form-item label="角色产品权限" prop="productId">
            <el-select v-model="add_form_data.productId">
              <el-option
                v-for="item in product_list"
                :value="item.dictCode"
                :key="item.id"
                :label="item.dictValue"
              ></el-option>
            </el-select>
            <!-- <el-input
              v-model="add_form_data.code"
              placeholder="请输入角色代号"
              show-word-limit
              maxlength="30"
            ></el-input> -->
          </el-form-item>
          <el-form-item label="状态">
            <el-radio v-model="add_form_data.status" :label="1">启用</el-radio>
            <el-radio v-model="add_form_data.status" :label="0">禁用</el-radio>
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input
              type="textarea"
              rows="4"
              v-model="add_form_data.description"
              placeholder="请输入角色描述"
              show-word-limit
              maxlength="300"
            ></el-input>
          </el-form-item>
          <el-divider></el-divider>
          <div
            style="
              text-align: right;
              width: 88px;
              color: #606266;
              margin-top: 10px;
            "
          >
            权限分配
          </div>
          <el-tree
            class="tree"
            :data="role_data"
            show-checkbox
            node-key="id"
            ref="tree"
            :props="defaultProps"
          />
          <div class="tr m_top10">
            <el-button @click=";(show_box = false), resetForm(addroleform)"
              >取消</el-button
            >
            <el-button
              type="primary"
              @click="submit(addroleform)"
              :loading="loading"
              >保存</el-button
            >
          </div>
        </el-form>
      </template>
    </el-drawer>
    <dialog_box
      @submit_delete="submit_delete"
      @submit_edit="submit_edit"
      @close="show_delete_box = false"
      :delete_name="delete_name"
      :show_delete_box="show_delete_box"
      :delete_box_status="delete_box_status"
    ></dialog_box>
  </div>
</template>
<script lang="ts" setup>
import { check_role, handle_search_key } from '@/utils/check_role' // 权限校验
import search from '@/view/components/search.vue'
import dialog_box from '@/view/components/dialog_box.vue'
import table_edit from '@/view/components/table_edit.vue'
import setTable from '@/view/components/setTable.vue'
import {
  onMounted,
  ref,
  onUnmounted,
  nextTick,
  reactive,
  computed,
  watch,
} from 'vue'
import { FormInstance, ElMessage, FormRules } from 'element-plus'
import axios from '@/service/HttpRequest'
import serviceApi from '@/service/api'
import EventBus from '@/utils/EventBus'
import { useStore } from 'vuex'
const store = useStore()
// type FormInstance = InstanceType<typeof ElForm>
const addroleform = ref<FormInstance>()
const customize = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('请输入角色代号'))
  }
  setTimeout(() => {
    var reg = new RegExp('[\\u4E00-\\u9FFF]+', 'g')
    if (reg.test(value)) {
      callback(new Error('角色代号不能包含汉字'))
    } else {
      callback()
    }
  }, 1000)
}
const rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  code: [{ required: true, validator: customize, trigger: 'blur' }],
  productId: [{ required: true, message: '请选择产品权限', trigger: 'change' }],
})
const has_role_list = ref([
  { path: 'role/status', has_role: false },
  { path: 'role/put', has_role: false },
  { path: 'role/delete', has_role: false },
  { path: 'role/post', has_role: false },
])
const loading = ref(false)
// const total = ref()
const show_box = ref(false)
const page_data = ref({
  current: 1,
  description: '',
  name: '',
  code: '',
  pageSize: 100,
  status: '',
})
const add_form_data = ref({
  id: '',
  name: '',
  code: '',
  status: 1,
  description: '',
  platformType: '2',
  roleRouteDealVOList: [],
  productId: '',
})
const defaultProps = {
  children: 'children',
  label: 'label',
  isLeaf: 'leaf',
}
const height_size = ref(1) // 行高
const header_list = ref([
  {
    label: '名称',
    value: '',
    showTable: true,
    type: 'input',
    isShow: true,
    options: [],
  },
  {
    label: '代号',
    value: '',
    showTable: true,
    type: 'input',
    isShow: true,
    options: [],
  },
  {
    label: '状态',
    value: '',
    showTable: true,
    type: 'select',
    isShow: false,
    options: [
      { label: '已启用', value: '1' },
      { label: '已禁用', value: '0' },
    ],
  },
  {
    label: '角色描述',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
  },
])
const list = ref()
// 总权限组
const role_data = computed(() => {
  return store.state.role_list
}) // 权限组
const tree = ref(null)
const product_list = ref()
onMounted(() => {
  product_list.value = JSON.parse(JSON.stringify(store.state.product_list))
  product_list.value.forEach((item) => {
    let has_product = store.state.current_enterprise_level.some((item1) => {
      return item1.productId == item.dictCode
    })
    if (has_product) item.is_show = true
    else item.is_show = false
  })
  product_list.value = product_list.value.filter((item) => {
    return item.is_show
  })
  console.log(product_list.value)
  has_role_list.value.forEach((item) => {
    item.has_role = check_role(item)
  })
  EventBus.on('refresh', () => {
    // 刷新
    get_list()
    ElMessage.success('刷新成功！')
  })
  get_list()
})
onUnmounted(() => {
  EventBus.off('refresh')
})
// 弹窗打开时 给所有角色默认都有的权限
watch(show_box, (a, b) => {
  //   console.log(a, b)
  if (a) {
    set_default_role()
  }
})
const set_default_role = () => {
  let default_checked = []
  store.state.check_role_list.forEach((item) => {
    if (item.disabled) {
      default_checked.push(item.id)
    }
  })
  nextTick(() => {
    default_checked.forEach((item) => {
      let node = tree.value.getNode(item)
      if (node.isLeaf) {
        tree.value.setChecked(node, true)
      }
    })
  })
}
const submit = async (formEl: FormInstance | undefined) => {
  var a = tree.value.getCheckedNodes(false, true) // 获取选中节点  包含半选中
  console.log(a)
  if (!a.length) {
    ElMessage.warning('至少分配一项权限！')
    return
  }
  if (loading.value) {
    return
  }
  loading.value = true
  for (let i in a) {
    // 拥有菜单权限  赋予列表全选
    if (
      (a[i].type == 2 || a[i].type == 3) &&
      a[i].children &&
      a[i].children.length
    ) {
      a.push(a[i].children[0])
    }
  }
  for (let i in a) {
    var b = { routeId: a[i].id }
    add_form_data.value.roleRouteDealVOList.push(b)
  }
  await formEl.validate((valid) => {
    console.log(valid, add_form_data.value)
    if (valid) {
      axios
        .request({
          url:
            add_form_data.value.id == ''
              ? serviceApi.role_crud
              : serviceApi.role_crud + '/' + add_form_data.value.id,
          method: add_form_data.value.id == '' ? 'post' : 'put',
          data: add_form_data.value,
        })
        .then((res) => {
          console.log(res)
          ElMessage.success('操作成功！')
          setTimeout(() => {
            get_list()
            show_box.value = false
            loading.value = false
          }, 1000)
        })
        .catch((error) => {
          loading.value = false
          ElMessage.error(error)
        })
    } else {
      loading.value = false
    }
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  add_form_data.value = {
    id: '',
    name: '',
    code: '',
    status: 1,
    platformType: '2',
    description: '',
    roleRouteDealVOList: [],
    productId: '',
  }
  tree.value.setCheckedKeys([], true)
}
const search_key = () => {
  console.log(header_list.value)
  page_data.value = {
    current: 1,
    code: header_list.value[1].value,
    name: header_list.value[0].value,
    description: header_list.value[3].value,
    pageSize: 10,
    status: parseInt(header_list.value[2].value) as any,
  }
  get_list()
}
const show_delete_box = ref(false)
const delete_box_status = ref()
const delete_id = ref()
const delete_name = ref()
const submit_delete = () => {
  axios
    .request({
      url: serviceApi.role_crud + '/' + delete_id.value,
      method: 'delete',
    })
    .then((res) => {
      console.log(res)
      ElMessage.success('删除成功！')
      setTimeout(() => {
        show_delete_box.value = false
        get_list()
      }, 1000)
    })
    .catch((error) => {
      show_delete_box.value = false
      ElMessage.error(error)
    })
}
const submit_edit = () => {
  axios
    .request({
      url:
        delete_box_status.value == 2
          ? serviceApi.role_disable + '/' + delete_id.value
          : serviceApi.role_enable + '/' + delete_id.value,
      method: 'put',
    })
    .then((res) => {
      console.log(res)
      ElMessage.success('操作成功！')
      setTimeout(() => {
        show_delete_box.value = false
        get_list()
      }, 1000)
    })
    .catch((error) => {
      ElMessage.error(error)
      show_delete_box.value = false
    })
}
const delete_role = (e) => {
  console.log(e)
  delete_box_status.value = e.type
  show_delete_box.value = true
  delete_id.value = e.item.id
  delete_name.value = e.item.name
}
const update_role = (e) => {
  axios
    .request({ url: serviceApi.role_crud + '/' + e.row.id, method: 'get' })
    .then((res) => {
      console.log(res)
      add_form_data.value = {
        id: res.data.id,
        platformType: '2',
        name: res.data.name,
        code: res.data.code,
        status: res.data.status ? 1 : 0,
        description: res.data.description,
        roleRouteDealVOList:
          res.data.roleRouteDTOList ?? '' == ''
            ? []
            : res.data.roleRouteDTOList,
        productId: res.data.productId ? res.data.productId : '',
      }
      let default_checked = []
      if ((res.data.roleRouteDTOList ?? '') !== '') {
        for (let i in res.data.roleRouteDTOList) {
          default_checked.push(res.data.roleRouteDTOList[i].routeId)
        }
      }
      console.log(default_checked)
      show_box.value = true
      nextTick(() => {
        default_checked.forEach((item) => {
          let node = tree.value.getNode(item)
          if (node.isLeaf) {
            tree.value.setChecked(node, true)
          }
        })
      })
    })
    .catch((error) => {
      ElMessage.error(error)
    })
}
const get_list = () => {
  loading.value = true
  axios
    .request({
      url: serviceApi.role_list,
      method: 'post',
      data: handle_search_key(page_data.value),
    })
    .then((res) => {
      console.log(res)
      list.value = res.data.content
      //   total.value = res.data.totalElements
      loading.value = false
    })
    .catch((error) => {
      loading.value = false
      ElMessage.error(error)
    })
}
const max_height = ref()
nextTick(() => {
  max_height.value = window.innerHeight - 320 // 不带分页的 table 高度
})
const treeToArray = (tree) => {
  var res = []
  for (const item of tree) {
    const { children, ...i } = item
    if (children && children.length) {
      res = res.concat(treeToArray(children))
    }
    res.push(i)
  }
  return res
}
</script>
<style lang="scss" scoped>
.tree {
  margin-top: 10px;
  max-height: 500px;
  overflow-y: scroll;
  border: 1px solid #acacac;
}
:deep(.el-switch__core) {
  width: 70px !important;
}
</style>
